#!/bin/bash

set -e
set -x

vip=10.0.0.43 # 虚拟IP

sysctl -w net.ipv4.ip_forward=1

iplist_path=config
i=2 # 服务器个数
while read -r line
do
    case $str in       
        *'#'*)
            continue
        ;;
        *)
            IFS=',' read -ra parts <<< "$line"
        ;;
    esac  
    
    pass="${parts[0]}" 
    address="${parts[1]}"
    hostname="${parts[2]}"
    if [ $address ];then
        sshpass -p$pass ssh -n $address yum install -y nginx
        sshpass -p$pass ssh -n $address "echo $hostname > /usr/share/nginx/html/index.html"
        sshpass -p$pass ssh -n $address systemctl enable --now nginx
        iptables -t nat -A PREROUTING -d $vip -p tcp -m tcp --dport 80 -m statistic --mode nth --every $i --packet 0 -j DNAT --to-destination $address:80
        iptables -t nat -A POSTROUTING -d $address -p tcp -m tcp --dport 80 -j SNAT --to-source $vip
        let i=i+1
    fi
done < $iplist_path


# iptables -t nat -A PREROUTING -d $vip -p tcp -m tcp --dport 80 -m statistic --mode nth --every 2 --packet 0 -j DNAT --to-destination $nginx01:80
# iptables -t nat -A POSTROUTING -d $nginx01 -p tcp -m tcp --dport 80 -j SNAT --to-source $vip

# iptables -t nat -A PREROUTING -d $vip -p tcp -m tcp --dport 80 -m statistic --mode nth --every 1 --packet 0 -j DNAT --to-destination $nginx02:80
# iptables -t nat -A POSTROUTING -d $nginx02 -p tcp -m tcp --dport 80 -j SNAT --to-source $vip


set +x
set +e